package com.guoyan.blockchain.common.client;

import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.hyperledger.fabric.sdk.security.CryptoSuite;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;

public class FabricClient {

    private HFClient instance;

    public HFClient getInstance() {
        return instance;
    }

    public FabricClient(User context) throws CryptoException, InvalidArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
        CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
        // setup the client
        instance = HFClient.createNewInstance();
        instance.setCryptoSuite(cryptoSuite);
        instance.setUserContext(context);
    }

    public ChannelClient createChannelClient(String name) throws InvalidArgumentException {
        Channel channel = instance.newChannel(name);
        return new ChannelClient(name, channel, this);
    }

    public Collection<ProposalResponse> deployChainCode(String chainCodeName, String chaincodePath, String codepath, TransactionRequest.Type type, String version, Collection<Peer> peers) throws InvalidArgumentException, ProposalException {
        InstallProposalRequest request = instance.newInstallProposalRequest();
        ChaincodeID.Builder chaincodeIDBuilder = ChaincodeID.newBuilder().setName(chainCodeName).setVersion(version);
        ChaincodeID chaincodeID = chaincodeIDBuilder.build();
        request.setChaincodeID(chaincodeID);
        request.setUserContext(instance.getUserContext());
        request.setChaincodeSourceLocation(new File(codepath));
        request.setChaincodeVersion(version);
//		ChaincodeEndorsementPolicy policy = new ChaincodeEndorsementPolicy();
//		request.setChaincodeEndorsementPolicy();
        request.setChaincodeLanguage(type);
        return instance.sendInstallProposal(request, peers);
    }

}
